<template>
  <view class="category-page">
    <view class="category-header">
      <text class="header-title">选择分类</text>
    </view>
    <view class="category-list">
      <view 
        v-for="item in categories" 
        :key="item.id"
        class="category-item"
        :class="{ active: currentCategory === item.id }"
        @click="selectCategory(item.id)"
      >
        <text class="category-name">{{ item.name }}</text>
        <text class="category-count">{{ item.count }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useImageStore } from '@/stores/image'
import { getCategoryList } from '@/api/image'

const imageStore = useImageStore()
const categories = ref([])
const currentCategory = ref('all')

onMounted(() => {
  loadCategories()
  // 获取当前分类
  currentCategory.value = imageStore.currentCategory
})

function loadCategories() {
  getCategoryList().then(res => {
    if (res.code === 200 && res.data) {
      categories.value = res.data
    }
  }).catch(err => {
    console.error('加载分类列表失败:', err)
    uni.showToast({
      title: err.message || '加载失败',
      icon: 'none'
    })
  })
}

function selectCategory(categoryId) {
  currentCategory.value = categoryId
  imageStore.setCategory(categoryId)
  // 切换到首页并刷新
  uni.switchTab({
    url: '/pages/index/index',
    success: () => {
      // 首页会自动刷新（通过 watch currentCategory）
    }
  })
}
</script>

<style scoped>
.category-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: calc(50px + env(safe-area-inset-bottom)); /* 为 tabbar 留出空间 */
}

.category-header {
  padding: 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.category-list {
  padding: 20rpx;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  transition: all 0.3s;
}

.category-item.active {
  background-color: #007aff;
  color: #fff;
}

.category-name {
  font-size: 32rpx;
  font-weight: 500;
}

.category-count {
  font-size: 28rpx;
  color: #999;
}

.category-item.active .category-count {
  color: rgba(255, 255, 255, 0.8);
}
</style>

